<?php

use App\Exceptions\AdminInvalidRequestException;
use App\Exceptions\InvalidRequestException;
use App\Helpers\KeyHandler;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use SuperEggs\DcatDistpicker\DcatDistpickerHelper;
use Illuminate\Http\Response;


if (!function_exists('successReturn')) {
    function successReturn($data = [], $code = Response::HTTP_OK, $msg = 'successful'): JsonResponse
    {
        return response()->json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ]);
    }
}

if (!function_exists('failReturn')) {
    function failReturn($msg, $code = Response::HTTP_BAD_REQUEST): JsonResponse
    {
        return response()->json([
            'code' => $code,
            'msg' => $msg,
        ], $code);
    }
}


function objectToArray($obj): array
{
    $obj = (array)$obj;
    foreach ($obj as $k => $v) {
        if (gettype($v) == 'resource') {
            return [];
        }
        if (gettype($v) == 'object' || gettype($v) == 'array') {
            $obj[$k] = (array)objectToArray($v);
        }
    }
    return $obj;

}


if (!function_exists('sendLoginSms')) {
    /**
     * 发送登录短信验证码
     * @throws InvalidRequestException
     */
    function sendLoginSms(string $phone, string $code, string $tpl_id)
    {
        try {
            $response = \Illuminate\Support\Facades\Http::get('http://v.juhe.cn/sms/send', [
                'mobile' => $phone,
                'tpl_id' => $tpl_id,
                'tpl_value' => '#code#=' . $code,
                'key' => config('juhe.sms.key')
            ]);
            $json = $response->json();
            if ($json['error_code']) {
                throw new InvalidRequestException($json['reason']);
            }
            //发送成功，code存入缓存
            Cache::set(sprintf(KeyHandler::LOGIN_SMS_CODE, $phone), $code, KeyHandler::LOGIN_SMS_CODE_TTL);
        } catch (Exception $exception) {
            throw new InvalidRequestException($exception->getMessage());
        }
    }
}

if (!function_exists('checkTelecom2')) {
    /**
     * 手机二元素校验
     * @param string $name
     * @param string $mobile
     * @return bool
     * @throws AdminInvalidRequestException
     */
    function checkTelecom2(string $name, string $mobile): bool
    {
        try {
            $response = \Illuminate\Support\Facades\Http::get('http://v.juhe.cn/telecom2/query', [
                'key' => config('juhe.telecom2.key'),
                'realname' => $name,
                'mobile' => $mobile
            ]);
            $json = $response->json();
            if ($json['error_code']) {
                throw new AdminInvalidRequestException($json['reason']);
            }
            return $json['result']['res'] === 1;
        } catch (Exception $exception) {
            throw new AdminInvalidRequestException($exception->getMessage());
        }
    }
}


if (!function_exists('checkLoginSms')) {
    /**
     * 校验登录短信验证码是否正确
     * @param $phone
     * @param $code
     * @return bool
     */
    function checkLoginSms($phone, $code): bool
    {
        $key = sprintf(KeyHandler::LOGIN_SMS_CODE, $phone);
        $check = Cache::get($key) === $code;
        if ($check) {
            //校验正确，清空验证码
            Cache::forget($key);
        }
        return $check;
    }
}


if (!function_exists('isMobileDevice')) {
    /**
     *判断客户端是否是移动设备
     * @return bool
     */
    function isMobileDevice(): bool
    {
        $userAgent = $_SERVER['HTTP_USER_AGENT'];
        // 使用正则表达式匹配常见的手机 User-Agent 字符串
        $pattern = "/(Mobile|iPod|iPhone|Android|BlackBerry|webOS|Windows Phone)/i";

        return (bool)preg_match($pattern, $userAgent);
    }
}


if (!function_exists('getAreaName')) {
    /**
     * 根据省市区code获取名称
     * @param $code
     * @return string
     */
    function getAreaName($code): string
    {
        return DcatDistpickerHelper::getAreaName($code);
    }
}


if (!function_exists('getBoolOption')) {
    //获取布尔值的选择项
    function getBoolOption(): array
    {
        return [
            0 => '否',
            1 => '是'
        ];
    }
}


/**
 * 获取可访问的阿里云对象存储地址
 * @param string $path 视频地址
 * @param int $expiration_hour 链接有效期，单位：小时
 */
if (!function_exists('getAliOssUrl')) {
    function getAliOssUrl($path, $expiration_hour = 1): string
    {
        $disk = config('admin.upload.disk');
        $storage = Storage::disk($disk);
        return $disk === 'oss' ? $storage->temporaryUrl($path, now()->addHours($expiration_hour)) : $storage->url($path);
    }
}

if (!function_exists('getAliOssDomain')) {
    function getAliOssDomain(): string
    {
        $disk = config('admin.upload.disk');
        if ($disk === 'oss') {
            return (config('filesystems.disks.oss.ssl') ? 'https://' : 'http://') . config('filesystems.disks.oss.bucket') . '.' . config('filesystems.disks.oss.endpoint');
        } else {
            return config('app.url') . '/storage';
        }

    }
}


function getDays($month): array
{
    $month = Carbon::parse($month);
    $day = $month->isCurrentMonth() ? now()->day : $month->copy()->lastOfMonth()->day;;
    $days = [];
    for ($i = 0; $i < $day; $i++) {
        $days[] = $month->copy()->addDays($i)->toDateString();
    }
    return $days;
}

function getMonths($date): array
{
    $month = Carbon::parse($date);
    $end = $month->isCurrentMonth() ? now()->month : $month->copy()->lastOfYear()->month;
    $start = $month->startOfYear();
    $arr = [];
    for ($i = 0; $i < $end; $i++) {
        $time = $month->copy()->addMonths($i);
        $arr[] = $time->year . '-' . str_pad($time->month, 2, 0, STR_PAD_LEFT);
    }
    return $arr;
}

function getHours($month): array
{
    $time = [];
    for ($i = 8; $i < 24; $i++) {
        $key = $month . ' ' . date($i);
        if ($i < 10 && ($i <= 0 || $i > 7)) {
            $key = $month . ' ' . date('0' . $i);
        }
        $time[] = $key;
    }
    return $time;
}

function getPercentage($num1, $num2): string
{
    return sprintf("%.2f", $num1 / $num2 * 100);
}

function getDivide($num1, $num2): string
{
    return sprintf("%.2f", $num1 / $num2);
}


//排序
function orderSort($direction, $field, $data)
{
    $sort = array(
        'direction' => $direction == 'asc' ? 'SORT_ASC' : 'SORT_DESC', //排序顺序标志 SORT_DESC 降序；SORT_ASC 升序
        'field' => $field,       //排序字段
    );
    $arrSort = array();
    foreach ($data as $unique => $row) {
        foreach ($row as $key => $value) {
            $arrSort[$key][$unique] = $value;
        }
    }
    array_multisort($arrSort[$sort['field']], constant($sort['direction']), $data);
    return $data;
}


//获取销售礼包数据
function getSaleData(): array
{
    $number = json_decode(file_get_contents(public_path('sale.txt')), true);
    return $number ?: ['registration' => 0, 'preferential' => 0, 'gift' => 0];
}


//获取唯一编号
function getUuid($len = 6): string
{
    $int = '';

    while (strlen($int) != $len) {
        $int .= mt_rand(0, 9);
    }
    return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . $int;
}


function convertNumberToLetter($number): string
{
    $letters = 'abcdefghijklmnopqrstuvwxyz';
    $letter = '';
    $number = $number * Complaint::NUMBER;
    while ($number > 0) {
        $remainder = $number % 26;
        $letter = $letters[$remainder] . $letter;
        $number = (int)($number / 26);
    }
    return $letter;
}

function convertLetterToNumber($letter): float|bool|int
{
    $letters = 'abcdefghijklmnopqrstuvwxyz';
    $number = 0;

    for ($i = 0; $i < strlen($letter); $i++) {
        $char = $letter[$i];
        $index = strpos($letters, $char);
        $number = $number * 26 + $index;
    }
    return $number / Complaint::NUMBER;
}

//文件大小显示转换
if (!function_exists('getRealSize')) {
    function getRealSize($size): string
    {
        $kb = 1024;
        $mb = 1024 * $kb;
        $gb = 1024 * $mb;
        $tb = 1024 * $gb;
        if ($size < $kb) {
            return $size . 'B';
        } elseif ($size < $mb) {
            return round($size / $kb, 2) . 'KB';
        } elseif ($size < $gb) {
            return round($size / $mb, 2) . 'MB';
        } elseif ($size < $tb) {
            return round($size / $gb, 2) . 'GB';
        } else {
            return round($size / $tb, 2) . 'TB';
        }
    }
}

if (!function_exists('secondsToTime')) {
    /**
     * 把秒转成时间格式
     * @param $init
     * @return string
     */
    function secondsToTime($init): string
    {
        $hours = floor($init / 3600);
        $minutes = str_pad(floor(($init / 60) % 60), 2, 0, STR_PAD_LEFT);
        $seconds = str_pad(floor(($init % 60) % 60), 2, 0, STR_PAD_LEFT);;
        return $hours ? $hours . ':' . $minutes . ':' . $seconds : $minutes . ':' . $seconds;

    }
}






